package com.cnh.o2o.web.frontend;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cnh.o2o.dto.UserAwardMapExecution;
import com.cnh.o2o.entity.Award;
import com.cnh.o2o.entity.PersonInfo;
import com.cnh.o2o.entity.Shop;
import com.cnh.o2o.entity.UserAwardMap;
import com.cnh.o2o.enums.UserAwardMapStateEnum;
import com.cnh.o2o.service.AwardService;
import com.cnh.o2o.service.PersonInfoService;
import com.cnh.o2o.service.UserAwardMapService;
import com.cnh.o2o.util.CodeUtil;
import com.cnh.o2o.util.HttpServletRequestUtil;
import com.cnh.o2o.util.ShortNetAddressUtil;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;

@Controller
@RequestMapping("/frontend")
public class MyAwardController {
	@Autowired
	private UserAwardMapService userAwardMapService;
	@Autowired
	private AwardService awardService;
	@Autowired
	private PersonInfoService personInfoService;
	private static String URLPREFIX = "https://open.weixin.qq.com/connect/oauth2/authorize?"
			+ "appid=wxd7f6c5b8899fba83&"
			+ "redirect_uri=115.28.159.6/myo2o/shop/exchangeaward&"
			+ "response_type=code&scope=snsapi_userinfo&state=";
	private static String URLSUFFIX = "#wechat_redirect";

	@RequestMapping(value = "/listuserawardmapsbycustomer", method = RequestMethod.GET)
	@ResponseBody
	private Map<String, Object> listUserAwardMapsByCustomer(
			HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		//分页信息
		int pageIndex = HttpServletRequestUtil.getInt(request, "pageIndex");
		int pageSize = HttpServletRequestUtil.getInt(request, "pageSize");
		//session中获取用户信息
		PersonInfo user = (PersonInfo) request.getSession().getAttribute("user");
		//判空
		if ((pageIndex > -1) && (pageSize > -1) && (user != null) && user.getUserId()!=null) {
			UserAwardMap userAwardMapCondition = new UserAwardMap();
			userAwardMapCondition.setUser(user);
			long shopId = HttpServletRequestUtil.getLong(request, "shopId");
			if (shopId > -1) {
				//
				Shop shop = new Shop();
				shop.setShopId(shopId);
				userAwardMapCondition.setShop(shop);
			}
			String awardName = HttpServletRequestUtil.getString(request, "awardName");
			if (awardName != null) {
				//
				Award award = new Award();
				award.setAwardName(awardName);
				userAwardMapCondition.setAward(award);
			}
			//分页条件查询
			UserAwardMapExecution ue = userAwardMapService.listUserAwardMap(
					userAwardMapCondition, pageIndex, pageSize);
			modelMap.put("userAwardMapList", ue.getUserAwardMapList());
			modelMap.put("count", ue.getCount());
			modelMap.put("success", true);
		} else {
			modelMap.put("success", false);
			modelMap.put("errMsg", "empty pageSize or pageIndex or userId");
		}
		return modelMap;
	}

	@RequestMapping(value = "/adduserawardmap", method = RequestMethod.POST)
	@ResponseBody
	private Map<String, Object> addUserAwardMap(HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		//session中获取用户信息
		PersonInfo user = (PersonInfo) request.getSession()
				.getAttribute("user");
		//
		Long awardId = HttpServletRequestUtil.getLong(request, "awardId");
		//封装查询条件  用户奖品映射对象
		UserAwardMap userAwardMap = compactUserAwardMap4Add(user, awardId);
		//判空
		if (userAwardMap != null) {
			try {
				//添加兑换信息
				UserAwardMapExecution se = userAwardMapService
						.addUserAwardMap(userAwardMap);
				if (se.getState() == UserAwardMapStateEnum.SUCCESS.getState()) {
					modelMap.put("success", true);
				} else {
					modelMap.put("success", false);
					modelMap.put("errMsg", se.getStateInfo());
				}
			} catch (RuntimeException e) {
				e.printStackTrace();
				modelMap.put("success", false);
				modelMap.put("errMsg", e.toString());
				return modelMap;
			}

		} else {
			modelMap.put("success", false);
			modelMap.put("errMsg", "请选择领取的奖品");
		}
		return modelMap;
	}
	
	@RequestMapping(value="/getawardbyuserawardid", method=RequestMethod.GET)
	@ResponseBody
	private Map<String, Object> getAwardById(HttpServletRequest request){
		Map<String, Object> modelMap = new HashMap<String, Object>();
		//
		Long userAwardId = HttpServletRequestUtil.getLong(request, "userAwardId");
		if (userAwardId > -1) {
			UserAwardMap userAwardMap = userAwardMapService.getUserAwardMapById(userAwardId);
			Award award = awardService.getAwardById(userAwardMap.getAward().getAwardId());
			modelMap.put("award", award);
			modelMap.put("usedStatus", userAwardMap.getUsedStatus());
			modelMap.put("userAwardMap", userAwardMap);
			modelMap.put("success", true);
		} else {
			modelMap.put("success", false);
			modelMap.put("errMsg", "empty awardId");
		}
		return modelMap;

	}
	
	
	//微信获取用户信息的api前缀
	private static String urlPrefix;
	//微信获取用户信息的api中间部分
	private static String urlMiddle;
	//后缀
	private static String urlSuffix;
	//微信回传给的响应添加用户奖品映射信息的url
	private static String exchangeUrl;
	
	@Value("${wechat.prefix}")
	public void setUrlPrefix(String urlPrefix) {
		MyAwardController.urlPrefix = urlPrefix;
	}
	@Value("${wechat.middle}")
	public void setUrlMiddle(String urlMiddle) {
		MyAwardController.urlMiddle = urlMiddle;
	}
	@Value("${wechat.suffix}")
	public void setUrlSuffix(String urlSuffix) {
		MyAwardController.urlSuffix = urlSuffix;
	}
	@Value("${wechat.exchange.url}")
	public void setAuthUrl(String exchangeUrl) {
		MyAwardController.exchangeUrl = exchangeUrl;
	}

	/**
	 * 生成奖品的领取二维码,供操作员扫描,证明已领取,微信扫一扫就能链接到对应的url
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/generateqrcode4award", method = RequestMethod.GET)
	@ResponseBody
	private void generateQRCode4Award(HttpServletRequest request,
			HttpServletResponse response) {
		//
		long userAwardId = HttpServletRequestUtil.getLong(request, "userAwardId");
		//
		UserAwardMap userAwardMap = userAwardMapService.getUserAwardMapById(userAwardId);
		//
		PersonInfo user = (PersonInfo) request.getSession().getAttribute("user");
		//
		if (userAwardMap != null && userAwardMap.getUser()!=null&& user != null && user.getUserId() != null
				&& userAwardMap.getUser().getUserId() == user.getUserId()
				&& userAwardMap.getUsedStatus() == 0) {
			//时间戳
			long timpStamp = System.currentTimeMillis();
			//将商品id,顾客id和timestamp传入content,赋值到state中,这样微信获取到这些信息后会回传到用户商品映射的添加方法
			//加上aaa是为了一会的在添加信息的方法里替换这些信息使用
			String content = "{aaauserAwardIdaaa:" + userAwardId
					+ ",aaacustomerIdaaa:" + user.getUserId()
					+ ",aaacreateTimeaaa:" + timpStamp + "}";
			try {
				//将content的信息先进行base64编码以避免特殊字符造成的干扰,之后拼接目标url
				String longUrl = urlPrefix + exchangeUrl + urlMiddle + URLEncoder.encode(content, "UTF-8") + urlSuffix;
				//将目标url转成短的url
				String shortUrl = ShortNetAddressUtil.getShortURL(longUrl);
				//调用二维码生成的工具类方法,传入短的url,生成二维码
				BitMatrix qrCodeImg = CodeUtil.generateQRCodeStream(shortUrl, response);
				//将二维码以图片流的形式输出到前端
				MatrixToImageWriter.writeToStream(qrCodeImg, "png", response.getOutputStream());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private UserAwardMap compactUserAwardMap4Add(PersonInfo user, Long awardId) {
		UserAwardMap userAwardMap = null;
		if (user != null && user.getUserId() != null && awardId != -1) {
			userAwardMap = new UserAwardMap();
			PersonInfo personInfo = personInfoService.getPersonInfoById(user
					.getUserId());
			Award award = awardService.getAwardById(awardId);
			Shop shop = new Shop();
			shop.setShopId(award.getShopId());
			userAwardMap.setUser(user);
			userAwardMap.setAward(award);
			userAwardMap.setShop(shop);
			//操作员
//			userAwardMap.setOperator(operator);
			userAwardMap.setPoint(award.getPoint());
			userAwardMap.setCreateTime(new Date());
			userAwardMap.setUsedStatus(1);
		}
		return userAwardMap;
	}
}
